<template>
	<page-meta :page-style="`overflow: ${moreVisible || serviceVisible || redPacketVisible ? 'hidden' : 'visible'}`"></page-meta>
	<!-- TODO 返回按钮 -->
	<view class="control-box">
		<view class="round music-round" :class="{'close': !isMusicOpen}" @click="handleMusicSwitch">
			<image src="/src/static/activity/detail/music-icon.png" mode="aspectFill"></image>
		</view>
		<view class="round dan-round" :class="{'close': !isDamnuOpen}" @click="handleDanmuSwitch">
			弹
		</view>
	</view>
	<view class="danmu-box" v-if="isDamnuOpen">
		<Danmuku 
		  :dumuList="dumuList" 
		  @loadMore="loadMore" 
		  :pageTotal="pageInfo.total"
		  style="width: 100%; margin: 0 auto;" 
		  ref="danmuRef" 
		  :isLoop="isLoop" 
		  :isSlot="isSlot"
		>
		  <template #danmuItem="{ danmu }">
		    <view
		      class="danmu-item"
		    >
		      <image 
		        :src="danmuImageObj[danmu?.type]" 
		        mode="aspectFill"
		      ></image>
		      <view class="text">
		        {{ danmu.text }}
		      </view>
		    </view>
		  </template>
		</Danmuku>
	</view>
	<image v-if="activityData?.locationMap1" class="landing-img" :src="activityData?.locationMap1" mode="widthFix"></image>
	<view class="statistics-box">
		<view class="total-row">
			<image class="paddy-icon" src="/src/static/activity/detail/paddy-icon.png" mode="aspectFill"></image>
			<view class="center">
				<text>名额上限 {{ statisticData?.orderLimit || 0 }}</text>
				<view class="unit">
					<image src="/src/static/activity/detail/dan-icon.png" mode="aspectFill"></image>
				</view>
			</view>
			<image class="paddy-icon right-icon" src="/src/static/activity/detail/paddy-icon.png" mode="aspectFill"></image>
		</view>
		<view class="card-row">
			<view class="card-item">
				<view class="value">{{ statisticData?.orderCount || 0 }}</view>
				<view class="label">订单</view>
			</view>
			<view class="card-item">
				<view class="value">{{ statisticData?.viewCount || 0 }}</view>
				<view class="label">游览</view>
			</view>
			<view class="card-item">
				<view class="value">{{ statisticData?.shareCount || 0 }}</view>
				<view class="label">分享</view>
			</view>
		</view>
		<view class="progress-row" v-if="progress >= 60">
			<view class="remaining">
				仅剩 {{ statisticData?.orderRemaining || 0 }}名额，速来抢购
			</view>
			<view class="progress" :style="{width: progress + '%'}">
				<view class="icon">
					<image src="/src/static/activity/detail/progress-icon.png" mode="aspectFill"></image>
				</view>
			</view>
		</view>
	</view>
	<view class="store-box">
		<view class="title-row">
			<view class="title">
				适用门店
				<image class="shadow" src="/src/static/activity/detail/title-shadow.png" mode="aspectFill"></image>
			</view>
		</view>
		<StoreCard :storeList="storeSliceList" :follow="false" />
		<view class="more-row">
			<view class="more haptics-feedback" v-if="!isSpread" @click="handleSpread">
				<text>更多门店({{ storeList.length - 3 }})</text>
				<image src="/src/static/activity/detail/right-icon.png" mode="aspectFill"></image>
			</view>
			<view class="collapse haptics-feedback" v-else @click="handleSpread">
				收起门店
				<nut-icon name="rect-up"></nut-icon>
			</view>
		</view>
	</view>
	<image v-if="activityData?.locationMap2" id="landing-img2" class="landing-img" :src="activityData?.locationMap2" mode="widthFix"></image>
	<view class="countdown-box">
		<view class="title">距离活动结束</view>
		<nut-countdown v-model="resetTime" :endTime="endSeconds">
			<view class="countdown-part-box">
				<div class="part-item">
					<text class="value">{{ resetTime.d }}</text>
					<text class="unit">天</text>
				</div>
				<div class="part-item">
					<text class="value">{{ resetTime.h }}</text>
					<text class="unit">时</text>
				</div>
				<div class="part-item">
					<text class="value">{{ resetTime.m }}</text>
					<text class="unit">分</text>
				</div>
				<div class="part-item">
					<text class="value">{{ resetTime.s }}</text>
					<text class="unit">秒</text>
				</div>
			</view>
		</nut-countdown>
	</view>
	<navigator url="/pages/activity/create/index" class="created-activity-box">
		<view class="created-btn haptics-feedback">
			我也要创建活动
		</view>
	</navigator>
	<view class="red-packet" @click="redPacketVisible = true">
		<view class="top-row">
			<image src="/src/static/activity/detail/hbjc-text.png" mode="aspectFill"></image>
		</view>
		<view class="bottom-row">
			<text class="value">{{ activityData?.redPacketCount || 0 }}</text>
			<text class="label">个待领</text>
		</view>
	</view>
	<view class="footer-block"></view>
	<view class="footer-box">
		<view class="left-btns">
			<view class="item-btn haptics-feedback" @click="moreVisible = true">
				<image src="/src/static/activity/detail/more-icon.png" mode="aspectFill"></image>
				<view class="label">更多</view>
			</view>
			<view class="item-btn haptics-feedback" @click="serviceVisible = true">
				<image src="/src/static/activity/detail/service-icon.png" mode="aspectFill"></image>
				<view class="label">客服</view>
			</view>
			<view class="item-btn haptics-feedback" @click="toWriteOff">
				<image src="/src/static/activity/detail/code-icon.png" mode="aspectFill"></image>
				<view class="label">核销</view>
			</view>
		</view>
		<view class="right-btns">
			<button open-type="share" class="btn share-btn">分享赚</button>
			<view v-if="isExpired" class="btn over-btn">活动已结束</view>
			<navigator v-else url="/pages/order/create/index" class="btn buy-btn">
				<image src="/src/static/activity/detail/lightning-icon.png" mode="aspectFill"></image>
				<text>立即抢购</text>
			</navigator>
		</view>
	</view>
	
	<MoreFunctions
		v-model:visible="moreVisible"
	/>
	
	<CustomerService
		v-model:visible="serviceVisible"
		:likeStoreData="likeStoreData"
	/>
	
	<RedPacketList
		v-model:visible="redPacketVisible"
	/>
	
	<nut-toast></nut-toast>
</template>

<script setup>
import Danmuku from '@/components/Danmuku/index.vue'
import StoreCard from '@/components/StoreCard/index.vue'
import MoreFunctions from './components/MoreFunctions.vue';
import CustomerService from './components/CustomerService.vue';
import RedPacketList from './components/RedPacketList.vue';
import barrageIcon1 from '@/static/activity/detail/barrage-icon1.png'
import barrageIcon2 from '@/static/activity/detail/barrage-icon2.png'
import barrageIcon3 from '@/static/activity/detail/barrage-icon3.png'
import musicUrl from '@/static/activity/detail/bg-music.mp3'
import { onLoad, onHide, onShareAppMessage } from '@dcloudio/uni-app'
import { ref, reactive, computed, onUnmounted, watch } from 'vue'
import { getActivityDetail, getActivityStatistics, getActivityDanmu } from '@/api/activity';
import { getStorelistByActivity, getLikeStoreApi } from '@/api/store';
import { viewMarkApi, shareMarkApi, viewSuccessMarkApi } from '@/api/mark';
import { useUserStore } from '@/store/user';
import storage from '@/utils/storage';
import dayjs from 'dayjs';

const toast = useToast()

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const sectionId = ref()
const shareUserId = ref()
const viewId = ref()
const activityId = ref()
const activityData = ref({})
const innerAudioContext = uni.createInnerAudioContext({
  useWebAudioImplement: false
})
const isMusicOpen = ref(true)

const endSeconds = ref(0)
const resetTime = ref({
	d: '00',
	h: '00',
	m: '00',
	s: '00'
})
const isExpired = computed(() => {
	if (!activityData.value?.endTime) {
		return true
	}
	return dayjs().isAfter(dayjs(activityData.value?.endTime));
});

const viewMark = async () => {
	try {
		if (!shareUserId.value || !userInfo.value?.id || !activityId.value) return;
		const res = await viewMarkApi({
			shareUserId: shareUserId.value,
			viewUserId: userInfo.value?.id,
			shareActivityId: activityId.value
		})
		viewId.value = res.data
	} catch {
	}
}

const scrollToElement = () => {
	const query = uni.createSelectorQuery()
	query.select(`#${sectionId.value}`).boundingClientRect(data => {
		if (data) {
			uni.pageScrollTo({
				scrollTop: data.top,
				duration: 300
			})
		}
	}).exec()
}

const getDetail = async () => {
	try {
		const res = await getActivityDetail({
			activityId: activityId.value,
		})
		activityData.value = res.data
		
		if (res.data?.musicUrl || musicUrl) {
			innerAudioContext.loop = true
			innerAudioContext.src = res.data?.musicUrl || musicUrl
			innerAudioContext.play()
		}
		
		endSeconds.value = dayjs(res.data.endTime).valueOf()
		
		if (sectionId.value) {
			nextTick(() => {
				setTimeout(() => {
					scrollToElement()
				}, 500)
			})
		}
	} catch {
	}
}

const handleMusicSwitch = () => {
	isMusicOpen.value = !isMusicOpen.value
	if (isMusicOpen.value) {
		innerAudioContext.play()
	} else {
		innerAudioContext.pause()
	}
}

const statisticData = ref({})
const progress = computed(() => {
	if (!statisticData.value?.orderRemaining && !statisticData.value?.orderLimit) {
		return 0
	}
	return Math.floor(((statisticData.value?.orderLimit - statisticData.value?.orderRemaining) / statisticData.value?.orderLimit) * 100)
})

const getStatistics = async () => {
	try {
		const res = await getActivityStatistics({
			activityId: activityId.value
		})
		statisticData.value = res.data
	} catch {
	}
}

const storeList = ref([])
const storeSliceList = ref([])
const isSpread = ref(false)

const handleSpread = () => {
	isSpread.value = !isSpread.value
	if (isSpread.value) {
		storeSliceList.value = storeList.value
	} else {
		storeSliceList.value = storeList.value?.slice(0, 3)
	}
}

const getStoreList = async () => {
	try {
		const res = await getStorelistByActivity({
			activityId: activityId.value
		})
		storeList.value = res.data || []
		storeSliceList.value = storeList.value?.slice(0, 3)
	} catch {
	}
}


const dumuList = ref([])
const isDamnuOpen = ref(false)
const isSlot = ref(true)
const isLoop = ref(true)
const pageInfo = ref({
	pageNum: 1,
	total: 0,
	pageSize: 10
})
const danmuRef = ref(null)
const danmuImageObj = {
	TROPHY: barrageIcon3,
	RED_ENVELOPE: barrageIcon1,
	DIAMOND: barrageIcon2,
}
const danmuArr = ref([])

const getDanmu = async () => {
	try {
		const res = await getActivityDanmu({
			activityId: activityId.value
		})
		danmuArr.value = res.data
		handleDanmuSwitch()
	} catch {
	}
}

const getBarrageList = () => {
	pageInfo.value.total = danmuArr.value.length
	pageInfo.value.pageSize = danmuArr.value.length
	dumuList.value = danmuArr.value
}

const handleDanmuSwitch = () => {
	isDamnuOpen.value = !isDamnuOpen.value
	if (isDamnuOpen.value) {
		getBarrageList()
	} else {
		danmuRef.value.clearFn()
	}
}

const loadMore = () => {
	if (dumuList.value.length === pageInfo.value.total) {
		return
	}
	pageInfo.value.pageNum++
	getBarrageList()
}


const browseTime = ref(0) // 浏览时间（秒）
const timer = ref(null) // 定时器
const isReady = ref(false) // 是否达到15秒

const viewSuccessMark = async () => {
	try {
		if (!shareUserId.value || !userInfo.value?.id || !activityId.value || !viewId.value) return;
		await viewSuccessMarkApi({
			shareUserId: shareUserId.value,
			viewUserId: userInfo.value?.id,
			shareActivityId: activityId.value,
			viewId: viewId.value
		})
	} catch {
	}
}

const startTimer = () => {
  timer.value = setInterval(() => {
    browseTime.value++
    if (browseTime.value >= 15) {
		viewSuccessMark()
		isReady.value = true
		clearInterval(timer.value)
    }
  }, 1000)
}

// const handleRedPacket = () => {
// 	if (!isReady.value) {
// 		toast.text(`浏览15秒即可领取，当前浏览时间${browseTime.value}秒`)
// 		return
// 	}
// 	redPacketVisible.value = true
// }

const moreVisible = ref(false)

const serviceVisible = ref(false)
const likeStoreData = ref({})

const getLikeStore = async () => {
	try {
		const res = await getLikeStoreApi({
			activityId: activityId.value
		})
		likeStoreData.value = res.data
	} catch {
	}
}

const redPacketVisible = ref(false)



onLoad((options) => {
	sectionId.value = options?.sectionId
	activityId.value = options?.activityId
	shareUserId.value = options?.shareUserId
	viewMark()
	getDetail()
	getStatistics()
	getDanmu()
	getStoreList()
	startTimer()
	getLikeStore()
})

onUnmounted(() => {
	innerAudioContext.destroy()
	if (timer.value) {
		clearInterval(timer.value)
	}
})

const shareMark = async () => {
	try {
		await shareMarkApi({
			shareUserId: userInfo.value?.id,
			shareActivityId: activityId.value
		})
	} catch {
	}
}

onShareAppMessage(() => {
	shareMark()
	return {
		title: `邀请你参加${activityData.value?.name}`,
		path: `/pages/activity/detail/index?activityId=${activityId?.value}&shareUserId=${userInfo.value?.id}`,
		// imageUrl: ''
	}
})

const toWriteOff = () => {
	uni.navigateTo({
		url: '/pages/order/writeOff/index'
	})
}

const saveLastPage = () => {
	const pages = getCurrentPages()
	if (pages.length > 0) {
		const currentPage = pages[pages.length - 1]
		const route = currentPage.route
		const options = currentPage.options

		storage().set('lastPagePath', {
			route: route,
			options: options,
		})
	}
}

onHide(() => {
	saveLastPage()
})
</script>

<style lang="scss" scoped>
.control-box {
	position: absolute;
	top: 190rpx;
	right: 20rpx;
	z-index: 100;
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	.round {
		position: relative;
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1rpx solid #fff;
		border-radius: 50%;
	}
	.music-round {
		image {
			width: 28rpx;
			height: 28rpx;
		}
	}
	.dan-round {
		font-size: 24rpx;
		font-weight: 700;
		color: #fff;
	}
	.close::before {
		content: '';
		position: absolute;
		left: 50%;
		top: 50%;
		width: 40rpx;
		height: 1rpx;
		transform: translate(-50%, -50%) rotate(45deg);
		background-color: #fff;
	}
}
.danmu-box {
	position: absolute;
	left: 0;
	right: 0;
	top: 150rpx;
	width: 100%;
	height: 350rpx;
	z-index: 10;
	.danmu-item {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 6rpx;
		padding: 0 14rpx 0 10rpx;
		height: 44rpx;
		border-radius: 44rpx;
		background-color: rgba(0, 0, 0, 0.27);
		image {
			width: 26rpx;
			height: 26rpx;
		}
		.text {
			color: #fff;
		}
	}
}
.landing-img {
	width: 100%;
	display: block;
}
.statistics-box { 
	padding: 40rpx 60rpx;
	margin-bottom: 20rpx;
	background-color: #fff;
	.total-row {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		margin-bottom: 40rpx;
		.paddy-icon {
			width: 32rpx;
			height: 63rpx;
		}
		.right-icon {
			transform: scaleX(-1);
		}
		.center {
			display: flex;
			align-items: center;
			gap: 8rpx;
			text {
				font-size: 26rpx;
				color: #4F4F4F;
				transform: scaleY(1.2);
			}
			.unit {
				overflow: hidden;
				width: 28rpx;
				height: 28rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50%;
				background-color: #3B3B3B;
				image {
					width: 20rpx;
					height: 28rpx;
				}
			}
		}
	}
	.card-row {
		display: flex;
		justify-content: space-between;
		gap: 60rpx;
		margin-bottom: 40rpx;
		.card-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 20rpx;
			border-radius: 20rpx;
			background-color: #FBFBFD;
			.value {
				font-size: 40rpx;
				margin-bottom: 6rpx;
			}
			.label {
				color: #717C99;
			}
			&:nth-child(1) {
				box-shadow: 6rpx 6rpx 0px #8282FF;
				.value {
					font-weight: 700;
					color: #6161FF;
				}
			}
			&:nth-child(2) {
				box-shadow: 6rpx 6rpx 0px #FFE0B3;
			}
			&:nth-child(3) {
				box-shadow: 6rpx 6rpx 0px #C6E6F7;
			}
		}
	}
	.progress-row {
		position: relative;
		height: 40rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-radius: 40rpx;
		background-color: #FFE3E3;
		.remaining {
			color: #fff;
			font-size: 20rpx;
			transform: scaleY(1.4);
			margin-left: 24rpx;
			z-index: 1;
		}
		.progress {
			position: absolute;
			left: 0;
			top: 0;
			height: 100%;
			border-radius: 40rpx;
			background-color: #FE5455;
			.icon {
				position: absolute;
				top: 50%;
				right: -24rpx;
				width: 48rpx;
				height: 48rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50%;
				transform: translateY(-50%);
				background: linear-gradient(90deg, #FFE44F 0%, #FFCB24 100%);
				image {
					width: 18rpx;
					height: 24rpx;
					margin-left: 2rpx;
				}
			}
		}
	}
}
.store-box { 
	padding: 0 32rpx;
	margin-bottom: 20rpx;
	background-color: #fff;
	.title-row {
		display: flex;
		justify-content: center;
		padding: 40rpx 0;
		.title {
			position: relative;
			font-size: 40rpx;
			font-weight: 700;
			z-index: 1;
			.shadow {
				position: absolute;
				left: 26rpx;
				top: 16rpx;
				width: 168rpx;
				height: 54rpx;
				z-index: -1;
			}
		}
	}
	.more-row {
		padding: 20rpx 32rpx;
		.more {
			padding: 20rpx 0;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 6rpx;
			text {
				font-size: 24rpx;
				color: #666;
			}
			image {
				width: 30rpx;
				height: 30rpx;
			}
		}
		.collapse {
			padding: 20rpx 0;
			text-align: center;
			font-size: 24rpx;
			color: #666;
			:deep(.nut-icon-rect-up) {
				font-size: 24rpx;
				color: #666;
				height: 20rpx;
			}
		}
	}
}
.countdown-box {
	padding: 28rpx 60rpx 46rpx;
	background: linear-gradient(135deg, #4D2D04 0%, #000 100%);
	.title {
		text-align: center;
		font-size: 38rpx;
		color: #FFBE68;
		transform: scaleY(1.2);
		margin-bottom: 40rpx;
	}
	.countdown-part-box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 30rpx;
		.part-item {
			flex: 1;
			height: 96rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 6rpx;
			border-radius: 20rpx;
			border: 2rpx solid #545454;
			background-color: #262626;
			.value {
				font-size: 38rpx;
				color: #FFBE68;
				transform: scaleY(1.2);
			}
			.unit {
				font-size: 36rpx;
				color: #BDBDBD;
				transform: scaleY(1.2);
			}
		}
	}
}
.created-activity-box {
	padding: 72rpx 0;
	display: flex;
	justify-content: center;
	background-color: #FFF1DE;
	.created-btn {
		width: 314rpx;
		height: 100rpx;
		border-radius: 100rpx;
		border: 10rpx solid #FFB56B;
		background-color: #FF8D1A;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		color: #fff;
	}
}
.red-packet {
	position: fixed;
	right: 0;
	bottom: calc(114rpx + 50rpx + constant(safe-area-inset-bottom));
	bottom: calc(114rpx + 50rpx + env(safe-area-inset-bottom));
	width: 122rpx;
	height: 70rpx;
	border-radius: 10rpx 0 0 10rpx;
	overflow: hidden;
	.top-row {
		height: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #FF8D1A;
		image {
			width: 102rpx;
			height: 26rpx;
		}
	}
	.bottom-row {
		height: 50%;
		text-align: center;
		background: linear-gradient(90deg, #2BE6F2 0%, #C78CFA 100%);
		.value {
			font-size: 24rpx;
			font-weight: 700;
		}
		.label {
			font-size: 24rpx;
			font-weight: 700;
			color: #3D3D3D;
		}
	}
}
.footer-block {
	height: calc(114rpx + constant(safe-area-inset-bottom));
	height: calc(114rpx + env(safe-area-inset-bottom));
}
.footer-box {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 100;
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 40rpx;
	height: calc(114rpx + constant(safe-area-inset-bottom));
	height: calc(114rpx + env(safe-area-inset-bottom));
	padding: 0 40rpx;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	background-color: #fff;
	.left-btns {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 48rpx;
		.item-btn {
			text-align: center;
			image {
				width: 34rpx;
				height: 34rpx;
			} 
			.label {
				font-size: 24rpx;
				color: #393939;
			}
		}
	}
	.right-btns {
		display: flex;
		align-items: center;
		justify-content: space-between;
		gap: 20rpx;
		.btn {
			width: 176rpx;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 4rpx;
			border-radius: 70rpx;
			font-size: 30rpx;
			font-weight: 700;
			color: #fff;
		}
		.share-btn {
			background: linear-gradient(229.24deg, #FF8D1A 0%, #FFA940 50.74%, #FFC966 100%);
		}
		.over-btn {
			background-color: #ccc;
		}
		.buy-btn {
			background: linear-gradient(90deg, #FB0844 0%, #FB3E24 100%);
			image {
				width: 30rpx;
				height: 38rpx;
			}
		}
	}
}
</style>